# !/usr/local/bin/python3
# -*- encoding: utf-8 -*-
# @FileName :   Scheduler.py
# @DateTime :   2022/8/25 | 19:44
# @Author   :   IoTus3
# @GitHub   :   https://gitee.com/IoTus3
# @Contact  :   xianglin.fu3@gmail.com
# @License  :   (C)Copyright 2022-2023, LinYuStudio-NLPR-CASIA
# @Editor   :   Power by PyCharm
# @Desc     :   调度器


# 导入线程类
from src.main.utils.Thread import TaskThread, StopThread
from src.main.conf.conf import logPath

import os


class Scheduler(object):
    def __init__(self):
        self.thread_list = []
        self.window = None
        self.terminate = False  # 是否停止

    def start(self, window, fn_start, fn_stop, fn_counter, fn_failure, fn_update_price, fn_email):
        self.window = window
        self.terminate = False

        # 获取表格中的所有数据，每一行创建一个线程去执行监控
        # 拿到表格的索引
        for row_index in range(0, window.mainTable.rowCount()):
            asin = window.mainTable.item(row_index, 0).text().strip()
            status_text = window.mainTable.item(row_index, 6).text().strip()

            file_name = "{}.log".format(asin)
            if not os.path.exists(logPath):
                os.makedirs(logPath)
            file_path = logPath + file_name

            # 只有状态为待执行中才创建线程
            if status_text != "待执行中":
                continue
            # 每个线程执行一次之后，需要实时更新状态 singal + callback
            t = TaskThread(self, file_path, row_index, asin, window)
            t.start_signal.connect(fn_start)
            t.email_signal.connect(fn_email)
            t.counter_signal.connect(fn_counter)
            t.fail_signal.connect(fn_failure)
            t.price_signal.connect(fn_update_price)
            t.stop_signal.connect(fn_stop)
            t.start()

            self.thread_list.append(t)

    def stop(self, fn_update):
        self.terminate = True
        # 创建线程 监测thread_list 中的数量 并实时更新到主窗体
        t = StopThread(self, self.window)
        t.update_signal.connect(fn_update)
        t.start()

    def distroy_thread(self, thread):
        self.thread_list.remove(thread)


# 单例模式
SCHEDULER = Scheduler()
